package com.wml.sellPhone.controller;

import com.wml.sellPhone.service.IEmailService;
import com.wml.sellPhone.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 发送邮件
 *
 * @author Cheryl
 * @date 2018-06-28 16:07
 */
@Controller
public class SendEmailController {

    @Autowired
    private IEmailService emailService;

    /**
     * 发送邮件
     *
     * @param email
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/sendEmail", method = RequestMethod.GET)
    public Map<String, Boolean> sendEmail(String email, HttpServletRequest request){
        Map<String, Boolean> exist = new HashMap<>();
        boolean mailExists = emailService.judgeEmail(email, request);
        exist.put("mailExists", mailExists);
        exist.put("status", false);
        // 如果邮箱存在，则发送邮件
        if (mailExists){
            String randomNum = createRandomNum();//随机生成6位数的验证码
            request.getSession().setAttribute("captcha", randomNum);//将验证码存入session中
            String content = "您好！您的邮箱验证码是：" + randomNum + " 。打死也不能告诉别人！";
            emailService.sendEmail(content,"手机网验证", email);
            System.out.println("------" + randomNum);
            exist.put("status", true);
        }

        return exist;
    }

    /**
     * 产生随机数
     * @return
     */
    public static String createRandomNum(){
        //获得随机数种子
        Long rand = System.currentTimeMillis();
        // 产生随机数
        int randomNum = new Random(rand).nextInt(1000000);
        //初始化一个随机数变量
        String randomNumStr = "" + randomNum;

        return randomNumStr;
    }

    /**
     * 验证验证码是否正确
     *
     * @param captcha
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verification", method = RequestMethod.GET)
    public Map verification(String captcha, HttpServletRequest request){
        Map<String, Boolean> correct = new HashMap<>();
        // 验证验证码是否正确
        if (captcha.equals(request.getSession().getAttribute(Constant.CAPTCHA))){
            correct.put("correct", true);
            request.getSession().removeAttribute(Constant.CAPTCHA);
        } else {
            correct.put("correct", false);
        }
        return correct;
    }
}
